package com.tianyadu.mmall.core.authentication.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 短信验证码配置类
 *
 * @author xueyj
 * @date 2019-11-14 22:45
 */
@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    /**
     * 登陆成功
     */
    @Autowired
    private AuthenticationSuccessHandler authSuccessHandler;

    /**
     * 登陆失败
     */
    @Autowired
    private AuthenticationFailureHandler authFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 添加拦截及认证信息
     *
     * @param http HttpSecurity
     * @author xueyj
     * @date 2019/11/14-22:46
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //  初始化短信验证码拦截器
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        //  设置短信验证码拦截器authenticationManager
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //  设置认证成功处理器
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authSuccessHandler);
        //  设置认证失败处理器
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authFailureHandler);

        // 身份验证提供者
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        //  添加用户查询服务信息
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

        //  添加处理短信验证拦截器信息，将自定义短信验证拦截器smsCodeAuthenticationFilter添加至UsernamePasswordAuthenticationFilter之后
        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}